/**
 * JAVACC DEMO 1.0
 * @copy right iussoft company All rights reserved.
 * @Package com.iussoft.security.filter
 */
package com.apache.security.filter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.apache.security.SecurityFilter;
import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;

/**
 * description:  跨站点请求伪造。修复任务： 拒绝恶意请求。
 * @author Hou Dayu 创建时间：2016-9-14
 */
public class HttpRefererFilter implements SecurityFilter {

	private Logger log = Logger.getLogger(HttpRefererFilter.class);

	/**
	 * TODO 跨站点请求伪造.  
	 */
	public int doFilterInvoke(HttpServletRequest request, HttpServletResponse response) throws IOException,
			ServletException {

		String referer = request.getHeader("Referer"); //REFRESH  
		if (StrUtil.isNotNull(referer)) {
			String basePath = request.getScheme() + "://" + request.getServerName();
			String refererUrl = ConfigUtil.getInstance().getValueByKey("refererUrl");
			String strs = basePath;
			if (StrUtil.isNotNull(refererUrl)) {
				strs = refererUrl + "," + basePath;
			}
			String strsUrls[] = strs.split(",");
			for (int i = 0; i < strsUrls.length; i++) {
				if (referer.startsWith(strsUrls[i])) {
					return 1;
				}
			}
			//log.info("当前请求地址为：" + referer + "，不是合法请求地址来源");
			request.getRequestDispatcher(request.getRequestURI()).forward(request, response);
			return 0;
		}
		return 1;
	}

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.apache.security.SecurityFilter#setErrorPage(java.lang.String)  
	 */
	public void setErrorPage(String errorPage) {
		// TODO Auto-generated method stub
	}

}
